<?php 
## include required files
/*******************************/
require_once '../../includefiles.php';
require_once '../../model/users.php';
require_once '../../model/membershipplan.php';
require_once '../../model/state.php';
require_once '../../model/city.php';
include_once("../../model/usermembership.php");
include_once("../../model/usermembershipdetail.php");
require_once '../../includes/classes/paypalfunction.php'; // Pay Pal pro Function file 
require_once '../../model/admindetails.php';
include_once '../../model/email.php';
include_once '../../model/paypal.php';
include_once '../../model/trade.php';

$objPlan = new Model_PLAN();
$objState = new Model_State();
$objCity = new Model_City();
$memberObj	= new Model_Membership();
$memberDetailObj = new Model_MembershipDetail();
$userObj = new Model_Users();
$adminObj = new Model_AdminDetails();
$emailObj = new Model_Email();
$paypalObj = new Model_Paypal();
$tradeObj = new Model_TRADE();

$userId = $_SESSION['getbids_id'];
$userDetArray = $userObj->getUserDetailsByUserId($userId);


if($_SESSION['user_type'] == '3')
{
	@header("location:".SITE_URL."/");
	exit;
}

if(!$_SESSION['cats']['list'] || !$_SESSION['cats']['subtotal'])
{
	@header("location:".SITE_URL."/myaccount/myservicelocation/");
	exit;
}


$payvars = $_SESSION['cats'];

if($payvars["payment"]['paymentmethod'] == 'paypal')
{
	if($_POST['payment_status']=='Completed')
	{
		$membershipArray = array();
		$membershipArray['amount'] = $payvars['total'];
		$membershipArray['user_id'] = $userId;
		$membershipArray['dateadded'] = date("Y-m-d H:i:s");
		$orderId = $memberObj->addOrder($membershipArray);
		
		
		$membershipplanArray 				    = 		array();	
		$membershipplanArray['user_id'] 		= 		$userId;
		$membershipplanArray['mem_id'] 			= 		$orderId;
		$membershipplanArray['plan_id'] 		= 		0;	
		$membershipplanArray['amount'] 	    	= 		$payvars['total'];
		$membershipplanArray['add_date']   		= 		date("Y-m-d H:i:s");
		$membershipplanArray['status_date'] 		= 		date("Y-m-d H:i:s");
		$getRandonUpper 					= 		strtoupper(getRandomNumber());
		$invoiceId 							= 		$payvars['invoice'];
		$orderCardArray['invoiceid']		= 		$invoiceId;
		$transactionId 						= 		$_REQUEST['receiver_id'];
		$membershipplanArray['transaction_id']   =       $transactionId;	
		$membershipplanArray['transaction_msg']  =       $httpParsedResponseAr["L_LONGMESSAGE0"];	 			
		$membershipplanArray['invoiceid']        =       $invoiceId;	
		$membershipplanArray['status_date']		= 		date("Y-m-d H:i:s");
		$membershipplanArray['status'] 			= 		"paid";
		$membershipplanArray['paymentfor'] 			= 		"categories costing";
		$membershipplanArray['pmethod'] 			= 		"Paypal";
		
		$membershipplanArray['subtotal'] 			= 	$payvars['subtotal'];
		$membershipplanArray['total'] 			= 		$payvars['total'];
		$membershipplanArray['tax'] 			= 		$payvars['tax'];
		
		$orderDealId 			    		= 		$memberDetailObj->addRecord($membershipplanArray); // add order
		/*********record added to membership plan***********/
		
		/*   update trade category */
		$trades = array();
		$tradelist = '';
		foreach($payvars['list'] as $chcat)
		{
				$trades[] = array("id"=>$chcat['id'],"expired_time"=>$chcat['expired_time']);	
				$order_items = array();
				$order_items['order_id'] = $orderDealId;
				$order_items['name'] = $chcat['trade_category'];
				$order_items['price'] = $chcat['price'];
				$order_items['type'] = "category" ;
				$tradelist.=$chcat['trade_category']."<br>";
				$tradeObj->addOrderItems($order_items);
		}
		
		$tradeObj->updateUserTrades($userId,$trades);
		// send email message
		// Email to Supplier				
		$email_message = $emailObj->getEmailById(23);
		$e_subject = $email_message['email_subject'];
		$message = $email_message['email_content']; 
		
		
		$to= trim($userDetArray["email"]);
		$adminEmail = $adminObj->getAdminDetails();
		$from = $adminEmail;
		$fromname= SITENAME;
						 
		$emailTemplate = file_get_contents('../../emailtemplate.html');
		$template_msg = str_replace('[USERNAME]',$userDetArray["username"] , $emailTemplate);
		$template_msg = str_replace('[SITENAME]',SITENAME , $template_msg);
		$template_msg = str_replace('[LOGO]','<img src="'.SITE_URL.'/uploads/logo/'.$imageDetails.'">', $template_msg);
		$template_msg = str_replace('[MESSAGE]',$message,$template_msg); 
		//echo $template_msg; exit;
		if(trim($to) != '')
		{
			//make pdf invoice
			$files = makeInvoicePDF($userId,$orderDealId);
			//@send_mail($to, $template_msg, $subject, $from, $fromname); 
			$mailer = new AttachMailer( $from,$to, $e_subject, $template_msg,$fromname);
			$mailer->attachFile($files[0].$files[1]);
			$mailer->send();
		}
		//Email to Admin
		
		//User REgister an acocunt (29)
		$email_message = $emailObj->getEmailById(29);
		$e_subject = $email_message['email_subject'];
		$message = $email_message['email_content']; 
		
		$subject = str_replace('[SITENAME]', SITENAME, $e_subject);		 
		$message = str_replace('[SITENAME]', SITENAME, $message);			
		$message = str_replace('[USERNAME]', $userDetArray["email"], $message);
		
		
		$message = str_replace('[FIRST_NAME]',$userDetArray["first_name"] , $message);
		$message = str_replace('[LAST_NAME]',$userDetArray["last_name"] , $message);
		$message = str_replace('[EMAIL]',$userDetArray["email"] , $message);
		$message = str_replace('[POSTAL_CODE]',$userDetArray["postalcode"] , $message);
		$message = str_replace('[CATEGORY_LIST]',$tradelist , $message);
		
		$message = str_replace('[SITE_LINK]', SITENAME, $message);
		
		$to= $email_message['from_email']; 
		$from = $email_message['from_email']; ;
		$fromname= SITENAME;
						 
		$emailTemplate = file_get_contents('emailtemplate.html');
		$template_msg = str_replace('[SITENAME]',SITENAME , $emailTemplate);
		$template_msg = str_replace('[LOGO]','<img src="'.SITE_URL.'/uploads/logo/'.$imageDetails.'">', $template_msg);
		$template_msg = str_replace('[MESSAGE]',$message,$template_msg); 
		
		//echo $template_msg; exit;
		if(trim($to) != '')
		@send_mail($to, $template_msg, $subject, $from, $fromname); 
		
		
		unset($_SESSION['cats']);
		$_SESSION['msg'] = "<div class='success_msg'><span>Your trades has been updated</span></div>";		
		header("Location: ".SITE_URL."/myaccount/myservicelocation/");
			
	}
	else
	{
		unset($_SESSION['cats']);
		$_SESSION['msg'] = "<div class='success_msg'><span>Payment fail</span></div>";
		header("Location: ".SITE_URL."/myaccount/fail/");
		exit;	
	}
}
else //nab
{
		$membershipArray = array();
		$membershipArray['amount'] = $payvars['total'];
		$membershipArray['user_id'] = $userId;
		$membershipArray['dateadded'] = date("Y-m-d H:i:s");
		$orderId = $memberObj->addOrder($membershipArray);
		
		
		$membershipplanArray 				    = 		array();	
		$membershipplanArray['user_id'] 		= 		$userId;
		$membershipplanArray['mem_id'] 			= 		$orderId;
		$membershipplanArray['plan_id'] 		= 		0;	
		$membershipplanArray['amount'] 	    	= 		$payvars['total'];
		$membershipplanArray['add_date']   		= 		date("Y-m-d H:i:s");
		$membershipplanArray['status_date'] 		= 		date("Y-m-d H:i:s");
		$getRandonUpper 					= 		strtoupper(getRandomNumber());
		$invoiceId 							= 		$payvars['invoice'];
		$orderCardArray['invoiceid']		= 		$invoiceId;
		$transactionId 						= 		$_REQUEST['receiver_id'];
		$membershipplanArray['transaction_id']   =       $transactionId;	
		$membershipplanArray['transaction_msg']  =       $httpParsedResponseAr["L_LONGMESSAGE0"];	 			
		$membershipplanArray['invoiceid']        =       $invoiceId;	
		$membershipplanArray['status_date']		= 		date("Y-m-d H:i:s");
		$membershipplanArray['status'] 			= 		"paid";
		$membershipplanArray['paymentfor'] 			= 		"categories costing";
		$membershipplanArray['pmethod'] 			= 		"NAB";
		
		$membershipplanArray['subtotal'] 			= 	$payvars['subtotal'];
		$membershipplanArray['total'] 			= 		$payvars['total'];
		$membershipplanArray['tax'] 			= 		$payvars['tax'];
		
		$orderDealId 			    		= 		$memberDetailObj->addRecord($membershipplanArray); // add order
		/*********record added to membership plan***********/
		
		/*   update trade category */
		$trades = array();
		$tradeslist = '';
		foreach($payvars['list'] as $chcat)
		{
				$trades[] = array("id"=>$chcat['id'],"expired_time"=>$chcat['expired_time']);	
				$order_items = array();
				$order_items['order_id'] = $orderDealId;
				$order_items['name'] = $chcat['trade_category'];
				$order_items['price'] = $chcat['price'];
				$order_items['type'] = "category" ;
				$tradeObj->addOrderItems($order_items);
				$tradelist.=$chcat['trade_category']."<br>";
				
		}
		
		$tradeObj->updateUserTrades($userId,$trades);
		// send email message
		// Email to Supplier				
		$email_message = $emailObj->getEmailById(23);
		$e_subject = $email_message['email_subject'];
		$message = $email_message['email_content']; 
		
		
		$to= trim($userDetArray["email"]);
		$adminEmail = $adminObj->getAdminDetails();
		$from = $adminEmail;
		$fromname= SITENAME;
						 
		$emailTemplate = file_get_contents('../../emailtemplate.html');
		$template_msg = str_replace('[USERNAME]',$userDetArray["username"] , $emailTemplate);		
		$template_msg = str_replace('[SITENAME]',SITENAME , $template_msg);
		$template_msg = str_replace('[LOGO]','<img src="'.SITE_URL.'/uploads/logo/'.$imageDetails.'">', $template_msg);
		$template_msg = str_replace('[MESSAGE]',$message,$template_msg); 
		//echo $template_msg; exit;
		if(trim($to) != '')
		{
			//make pdf invoice
			$files = makeInvoicePDF($userId,$orderDealId);
			//@send_mail($to, $template_msg, $subject, $from, $fromname); 
			$mailer = new AttachMailer( $from,$to, $e_subject, $template_msg,$fromname);
			$mailer->attachFile($files[0].$files[1]);
			$mailer->send();
		}
		
		//Email to Admin
		//User REgister an acocunt (29)
		$email_message = $emailObj->getEmailById(29);
		$e_subject = $email_message['email_subject'];
		$message = $email_message['email_content']; 
		
		$subject = str_replace('[SITENAME]', SITENAME, $e_subject);		 
		$message = str_replace('[SITENAME]', SITENAME, $message);			
		$message = str_replace('[USERNAME]', $userDetArray["email"], $message);
		
		
		$message = str_replace('[FIRST_NAME]',$userDetArray["first_name"] , $message);
		$message = str_replace('[LAST_NAME]',$userDetArray["last_name"] , $message);
		$message = str_replace('[EMAIL]',$userDetArray["email"] , $message);
		$message = str_replace('[POSTAL_CODE]',$userDetArray["postalcode"] , $message);
		$message = str_replace('[CATEGORY_LIST]',$tradelist , $message);
		
		$message = str_replace('[SITE_LINK]', SITENAME, $message);
		
		$to= $email_message['from_email']; 
		$from = $email_message['from_email']; ;
		$fromname= SITENAME;
						 
		$emailTemplate = file_get_contents('emailtemplate.html');
		$template_msg = str_replace('[SITENAME]',SITENAME , $emailTemplate);
		$template_msg = str_replace('[LOGO]','<img src="'.SITE_URL.'/uploads/logo/'.$imageDetails.'">', $template_msg);
		$template_msg = str_replace('[MESSAGE]',$message,$template_msg); 
		
		//echo $template_msg; exit;
		if(trim($to) != '')
		@send_mail($to, $template_msg, $subject, $from, $fromname); 
		
		unset($_SESSION['cats']);
		$_SESSION['msg'] = "<div class='success_msg'><span>Your trades has been updated</span></div>";		
		header("Location: ".SITE_URL."/myaccount/myservicelocation/");
		
}
exit;
?>

